'use strict';
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const mkdirp = require('mkdirp');

const Controller = require('egg').Controller;

class UploadController extends Controller {
  async uploadAvatar () {
    const { ctx, config } = this;
    try {
      // 获取文件
      const file = ctx.request.files[0];
      console.log('获取文件', file);
  
      // 读取文件数据
      // const fileData = await fs.readFileSync(file.filepath);
      const fileData = await fs.promises.readFile(file.filepath)
      console.log('fileData', fileData);
  
      // 获取当前日期
      const day = moment(new Date()).format('YYYYMMDD');
      console.log('1、获取当前日期', day);
  
      // 创建图片保存的路径
      const dir = path.join(config.uploadAvatarDir, day);
      console.log('2、创建图片保存的路径', dir);
  
      // 创建目录
      // await mkdirp(dir);
      await fs.promises.mkdir(dir, { recursive: true });
      // 生成路径返回
      const date = Date.now();
      const tempDir = path.join(dir, `${date}${path.extname(file.filename)}`);
      console.log('毫秒数 extname', date, path.extname(file.filename));
      console.log('返回图片保存的路径', tempDir);
  
      // 写入文件夹
      // fs.writeFile(tempDir, fileData);
      await fs.promises.writeFile(tempDir, fileData);
      ctx.body = {
        status: 200,
        desc: '上传成功',
        data: tempDir,
      };
    } catch (error) {
      console.error('上传失败:', error);
      ctx.body = {
        status: 500,
        desc: '上传失败',
        data: null,
      };
    } finally {
      // 清除临时文件
      ctx.cleanupRequestFiles();
    }
  }
}

module.exports = UploadController;
